import CryptoJS from 'crypto-js'
import U8array from './u8array.js'

function process(buffer, key,callBack) {
  var decryptedData = decrypt(buffer, key);
  //把解密后的对象再转为base64编码,这步是关键,跟解密文字不同
  var d64 = decryptedData.toString(CryptoJS.enc.Base64);
//   console.log('d64',d64);
  //   $(".img-thumbnail,.file-preview-image")[id].src = "data:image/jpeg;base64," + d64;
  callBack("data:image/jpeg;base64," + d64);
}

function decrypt(data, key) {
  // 接收的是ArrayBuffer
  let u8array = new Uint8Array(data);
  // 将u8array转换成WordArray
  let newdata = CryptoJS.enc.u8array.parse(u8array);
  // 要求密文是base64格式
  let ndata = newdata.toString(CryptoJS.enc.Base64);
  // 解密key
  let decrypted = CryptoJS.AES.decrypt(ndata, CryptoJS.enc.Latin1.parse(key), {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return decrypted;
}

//如果获取图片失败,尝试再获取一次
function retry(url,key,callBack) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "arraybuffer";
  xhr.onload = function () {
    if (xhr.status == 200) {
      process(xhr.response,key,callBack);
    }
  };
  xhr.send();
}

function getDecrypt(url,callBack) {
  let key = 'wPK8CxWaOwPuVzgs';
  let xhr = new XMLHttpRequest();
  if (url && url.indexOf(".ceb") != -1) {
    xhr.open("GET", url, true);
    xhr.responseType = "arraybuffer";
    xhr.timeout = 10000;
    xhr.onload = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            // console.log('xhr.response',xhr.response);
        process(xhr.response, key,callBack);

        } else {
            retry(url,key,callBack);
        }
      }
    };
    xhr.ontimeout = function () {
        retry(url,key,callBack);
    };
    xhr.send();
  }

}
export default {
    getDecrypt
}
